#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
class Solution
{
public:
    // 返回满足 csum >= target 的最小 index，如果不存在则返回-1
    int bisearch(vector<int> &csum, int l, int r, int target)
    {
        int i = l, j = r, mid = (l + r) / 2, ret = -1;
        while (i <= j)
        {
            mid = (i + j) / 2;
            if (csum[mid] < target)
            {
                i = mid + 1;
            }
            else
            {
                if (csum[mid] >= target)
                    ret = mid;
                j = mid - 1;
            }
        }
        return ret;
    }
    int minSubArrayLen(int s, vector<int> &nums)
    {
        if (nums.size() == 0)
            return 0;
        vector<int> csum(nums.size(), nums[0]);
        for (int i = 1; i < nums.size(); ++i)
        {
            csum[i] = csum[i - 1] + nums[i];
        }
        int i = 0, j = nums.size() - 1, ans = 0x7fffffff;
        for (i = 0; i < nums.size(); i++)
        {
            j = bisearch(csum, i, nums.size() - 1, s - nums[i] + csum[i]);
            if (j != -1)
                ans = min(ans, j - i + 1);
        }
        return ans != 0x7fffffff ? ans : 0;
    }
};